package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;

    /**
     * 查询商铺信息
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {
        //1. 缓存穿透
//        Shop shop = queryShopWithThrough(id);
        //                                                                     这里可以用id2->getById(id2)
        Shop shop = cacheClient.queryShopWithThrough(CACHE_SHOP_KEY,id,Shop.class,this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //2. 缓存击穿
//        Shop shop = queryShopWithMutex(id);

        //5. 返回商铺信息
        return Result.ok(shop);
    }

    //创建线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    //缓存逻辑过期
    public Shop queryShopWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1. 从redis查询
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //2. 判断是否存在
        if(StrUtil.isBlank(shopJson)){
            //3. 不存在，直接返回
            return null;
        }
        //4. 存在，先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();

        //5. 判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            //5.1 未过期，直接返回
            return shop;
        }
        //5.2 已过期，实现缓存重建
        String lockKey = LOCK_SHOP_KEY + id;
        //6.1 获取锁
        boolean tryLock = tryLock(lockKey);

        //6.2 判断是否获取成功
        if(tryLock){
            //6.3 判断缓存是否过期
            shopJson = stringRedisTemplate.opsForValue().get(key);

            //2. 判断是否存在
            if(StrUtil.isBlank(shopJson)){
                //3. 不存在，直接返回
                return null;
            }
            //4. 存在，先把json反序列化为对象
            redisData = JSONUtil.toBean(shopJson, RedisData.class);
            shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
            expireTime = redisData.getExpireTime();

            //5. 判断是否过期
            if(expireTime.isAfter(LocalDateTime.now())){
                //5.1 未过期，直接返回
                return shop;
            }

            //6.4 获取锁成功，开启独立线程实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //重建缓存
                    this.saveShopToRedis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });

        }

        //6.5 返回过期的数据
        return shop;

    }

    //缓存击穿（互斥锁）
    private Shop queryShopWithMutex(Long id){
        //1. 查询缓存
        String key = CACHE_SHOP_KEY + id;
        String shopJSon = stringRedisTemplate.opsForValue().get(key);

        //2. 判断是否存在
        if(StrUtil.isNotBlank(shopJSon)){
            return JSONUtil.toBean(shopJSon, Shop.class);
        }
        //2.1 判断是否为空
        if(shopJSon != null){
            return null;
        }

        //3. 未命中，查询数据库
        //3.1 判断数据库是否存在
        Shop shop = getById(id);

        //3.2 不存在，记录key值，写入空字符串
        if(shop == null){
            //3.3 将空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);

            return null;
        }

        //4 实现缓存重建
        //4.1 获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        try {
            boolean tryLock = tryLock(lockKey);

            //4.2 判断是否获取锁成功
            if(!tryLock){
                //4.3 失败则休眠重试
                Thread.sleep(50);
                return queryShopWithMutex(id);//这里递归调用，重复尝试获取锁
            }
            //注意 在获取锁成功后，需要再判断redis缓存是否存在
            //因为缓存重建是异步的，可能在缓存重建时，数据库中数据已经更新了，但是缓存中数据没有更新，导致缓存穿透
            shopJSon = stringRedisTemplate.opsForValue().get(key);

            //2. 判断是否存在
            if(StrUtil.isNotBlank(shopJSon)){
                return JSONUtil.toBean(shopJSon, Shop.class);
            }
            //2.1 判断是否为空
            if(shopJSon != null){
                return null;
            }

            //4.4 成功则根据id查询数据库
            shop = getById(id);

            //5. 不存在，返回错误，写入空值
            if(shop == null){
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }

            //6. 存在，写入redis
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //7. 释放互斥锁
            unLock(lockKey);
        }

        return shop;
    }

    //缓存穿透
    private Shop queryShopWithThrough(Long id){
        //1. 查询缓存
        String key = CACHE_SHOP_KEY + id;
        String shopJSon = stringRedisTemplate.opsForValue().get(key);

        //2. 判断是否存在
        if(StrUtil.isNotBlank(shopJSon)){
            return JSONUtil.toBean(shopJSon, Shop.class);
        }
        //2.1 判断是否为空
        if(shopJSon != null){
            return null;
        }

        //3. 未命中，查询数据库
        //3.1 判断数据库是否存在
        Shop shop = getById(id);

        //3.2 不存在，记录key值，写入空字符串
        if(shop == null){
            //3.3 将空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);

            return null;
        }

        //4. 存在，写入缓存
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop));

        //4.1 设置过期时间
        stringRedisTemplate.expire(key, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }

    public void saveShopToRedis(Long id, Long expireTime){
        Shop shop = getById(id);
        //创建RedisData对象
        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        redisData.setData(shop);

        //写入缓存
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id, JSONUtil.toJsonStr(redisData));
    }


    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);//使用hutool工具类转换，防止空指针异常,包装类转基本类型会有拆箱过程，若包装类是null，则拆箱时会抛出空指针异常
    }

    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
    /**
     * 更新商铺信息
     * @param shop
     * @return
     */
    @Override
    @Transactional//保证数据一致性
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空");
        }

        //1. 更新数据库
        updateById(shop);
        //2. 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);

        return Result.ok();
    }
}
